"use client";
import { useRouter, usePathname } from "next/navigation";
import { Dropdown, Menu, App } from "antd";
import type { MenuProps } from "antd";
import React, { useState, useEffect, useRef } from "react";
import { getNavigationItems } from "./NavigationTools";
import Image from "next/image";
import { useDispatch, useSelector } from "react-redux";
import { UserOutlined } from "@ant-design/icons";
import NotificationCenter from "../NotificationCenter";
import { topRightItems } from "./tools";
import { useListener } from "@/utils/sse/UseEventSource";
import { speechService } from "@/utils/SpeechService";

const Navigation: React.FC<{ hiddenUserInfo?: boolean; userInfo: any }> = ({
  hiddenUserInfo = false,
  userInfo,
}) => {
  const router = useRouter();
  const pathname = usePathname();
  const { notification } = App.useApp();
  const [userType, setUserType] = useState("");
  const [initialized, setInitialized] = useState(false);
  const [menuItems, setMenuItems] = useState<MenuProps["items"]>([]);

  // 用户的信息
  const windowTitle = process.env.NEXT_PUBLIC_WINDOW_TITLE || "我的应用";
  const [canPlayAudio, setCanPlayAudio] = useState(false);
  // 使用 ref 来避免回调中读取到过期的 state
  const canPlayAudioRef = useRef(canPlayAudio);

  // 同步 state 到 ref
  useEffect(() => {
    canPlayAudioRef.current = canPlayAudio;
  }, [canPlayAudio]);

  let user = useSelector((state: any) => state.auth.user);

  // const [userLocale, setUserLocale] = useState<any>(null);
  const [userInfoResult, setUserInfoResult] = useState({
    role_type: "",
    nick_name: "",
    dept_name: "",
    dept_id: "",
    parent_dept_name: "",
    avatar: "",
    user_type: "",
    sex: "",
    id: "",
  });

  const dispatch = useDispatch();

  useEffect(() => {
    // 只在客户端执行
    if (typeof window !== "undefined") {
      setUserType(localStorage.getItem("user_type") || "");
      setInitialized(true);
    }
  }, []);

  // 设置用户信息
  useEffect(() => {
    if (hiddenUserInfo) {
      return;
    }
    if (userInfo) {
      // 统一使用sex字段，如果没有则使用user_sex
      const userSex = userInfo.sex || userInfo.user_sex || "1";

      const newUserInfo = {
        nick_name: userInfo.nick_name || "",
        dept_name: userInfo.deptInfo?.dept_name || "",
        dept_id: userInfo.deptInfo?.dept_id || "",
        parent_dept_name: userInfo.deptInfo?.parent_dept_name || "",
        avatar:
          userSex === "0"
            ? "/icons/male-head-icon.png"
            : "/icons/female-head-icon.png",
        user_type: userInfo.user_type || "",
        sex: userSex,
        id: userInfo.id || "",
        role_type: userInfo.role_type || "",
      };
      setUserInfoResult(newUserInfo);
    }
  }, [userInfo]);

  // MQ监听器设置：组件挂载且 key 可用时订阅一次
  useEffect(() => {
    if (hiddenUserInfo) return;
    const key = userInfo?.deptInfo?.mq_routing_key;
    if (key) {
      setUpCanPlayAudio();
      useListener(key, (data) => {
        console.log("Navigation 收到 MQ 消息:", data);
        if (data.type === "message") {
          const ttsText = ` ${101}房${101}床${"坠床"}预警`;
          notification.open({
            message: "新预警",
            description: ttsText,
            type: "warning",
            duration: 4.5,
          });
          // 仅当用户已交互后播放音频
          if (canPlayAudioRef.current) {
            speechService.speak(ttsText);
          }
        }
      });
    }
  }, [userInfo]);

  // 设置音频播放
  const setUpCanPlayAudio = () => {
    const handleUserInteraction = () => {
      setCanPlayAudio(true);
      // 同步 ref
      canPlayAudioRef.current = true;
      window.removeEventListener("click", handleUserInteraction);
    };
    if (Notification.permission !== "granted") {
      Notification.requestPermission().then((permission) => {
        if (permission === "granted") {
          new Notification("请点击页面以启用音频功能");
        }
      });
    }
    window.addEventListener("click", handleUserInteraction);
  }

  // 退出登录
  const logout = async () => {
    localStorage.removeItem("sys_user");
    localStorage.removeItem("token");
    localStorage.removeItem("user_type");
    localStorage.removeItem("mq_routing_key");
    localStorage.removeItem("dept_id");
    localStorage.removeItem("user_menus"); // 清除菜单缓存
    window.location.href = "/login";
    setTimeout(() => {
      dispatch({
        type: "LOGOUT",
      });
    }, 200);
  };

  // 获取菜单数据
  useEffect(() => {
    const fetchMenuItems = async () => {
      if (!initialized) return;
      
      try {
        // 直接在这里计算用户信息，避免状态更新延迟问题
        let computedUserInfo = {
          role_type: "",
          nick_name: "",
          dept_name: "",
          dept_id: "",
          parent_dept_name: "",
          avatar: "",
          user_type: "",
          sex: "",
          id: "",
        };

        if (userInfo) {
          const userSex = userInfo.sex || userInfo.user_sex || "1";
          computedUserInfo = {
            nick_name: userInfo.nick_name || "",
            dept_name: userInfo.deptInfo?.dept_name || "",
            dept_id: userInfo.deptInfo?.dept_id || "",
            parent_dept_name: userInfo.deptInfo?.parent_dept_name || "",
            avatar:
              userSex === "0"
                ? "/icons/male-head-icon.png"
                : "/icons/female-head-icon.png",
            user_type: userInfo.user_type || "",
            sex: userSex,
            id: userInfo.id || "",
            role_type: userInfo.role_type || "",
          };
        }

        const items = await getNavigationItems(userType, computedUserInfo);
        setMenuItems(items || []);
      } catch (error) {
        console.error("加载导航菜单失败:", error);
        setMenuItems([]);
      }
    };

    fetchMenuItems();
  }, [userType, initialized, userInfo]);

  // 获取所有有效路径（包括子菜单）
  const getAllValidPaths = (items: MenuProps["items"]): string[] => {
    return (items || []).reduce<string[]>((paths, item) => {
      if (!item) return paths;
      paths.push(item.key as string);
      if ("children" in item && item.children) {
        paths.push(...getAllValidPaths(item.children));
      }
      return paths;
    }, []);
  };

  // 检查当前路径是否有效，如果无效则重定向到首页
  useEffect(() => {
    if (!initialized || !menuItems || menuItems.length === 0) return; // 未初始化或菜单为空时不检查
    
    const validPaths = getAllValidPaths(menuItems);
    
    // 如果是登录页面或明确不需要验证的路径，则不进行路由验证
    const skipValidationPaths = ['/login', '/', '/register'];
    if (pathname && skipValidationPaths.includes(pathname)) return;
    
    // 检查当前路径是否在有效路径列表中
    if (pathname && !validPaths.some(path => pathname.startsWith(path))) {
      router.push(`/login`);
    }
  }, [pathname, router, menuItems, initialized]);

  // 未初始化前显示加载状态或空内容
  if (!initialized) {
    return <div className="w-48 border-r"></div>;
  }

  return (
    <div className="flex flex-col h-full">
      <Menu
        className="w-30 border-r rounded-lg"
        mode="inline"
        theme="light"
        selectedKeys={[pathname || '']}
        items={menuItems}
        onClick={({ key }) => {
          // 特殊处理指挥中心点击，自动跳转到第一个子项
          if (key === "command-centre-parent") {
            // 使用userInfo prop直接获取role_type，避免state时序问题
            const roleType =
              userInfo?.role_type || userInfoResult.role_type || "";
            const fireCommandPath = `/agent/main/command-centre/fire-command/${roleType}`;
            router.push(fireCommandPath);
          } else {
            router.push(key);
          }
        }}
      />
      <div className="flex-1" />
      {!hiddenUserInfo && (
        <Dropdown
          menu={{ items: topRightItems(logout) }}
          arrow
          placement="topLeft"
          autoAdjustOverflow={false}
          getPopupContainer={(triggerNode) =>
            triggerNode.parentElement || document.body
          }
          overlayStyle={{
            position: "fixed",
            zIndex: 1050,
            minWidth: 120,
          }}
          trigger={["click"]}
        >
          <div className="flex items-center justify-start mb-2 ml-2">
            {/* 头像区域，使用相对定位作为通知中心的定位容器 */}
            <div className="relative">
              {userInfoResult.avatar ? (
                <Image
                  src={userInfoResult.avatar}
                  className="object-cover"
                  width={45}
                  height={45}
                  alt="用户头像"
                  style={{ borderRadius: "50%" }}
                />
              ) : (
                <div
                  className="w-[45px] h-[45px] bg-gray-400 flex items-center justify-center object-cover"
                  style={{ borderRadius: "50%" }}
                >
                  <UserOutlined style={{ fontSize: "24px", color: "white" }} />
                </div>
              )}
            </div>
            <div className="text-gray-500 font-bold text-[12px] leading-5 ml-2">
              {userInfoResult.nick_name || "加载中..."}
            </div>
          </div>
        </Dropdown>
      )}
    </div>
  );
};

export default Navigation;
